#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   comments.py
@Time    :   2023/05/08 11:49:28
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from typing import List, Union

from fastapi import APIRouter, Depends, Path, Request
from pydantic import parse_obj_as
from tortoise.exceptions import OperationalError
from tortoise.transactions import in_transaction

from ..models import PostModel as Post,CommentModel
from ..schemas import (CommentCreate,CommentUpdate,CommentOut,
                       CommentsListOut,CommentFilter,
                       FailResp, SuccessResp,PageSizePaginator, 
                       SingleResp,MultiResp,PageResp)
from ..utils.dbhelp import (get_comment_by_id,
                            get_comments_by_post)

router = APIRouter(prefix='/comments', tags=['评论管理'])


@router.post("", summary="添加评论")
async def create_comment(req: Request,
                         pid:int,
                         cid:int,
                         comment: CommentCreate):
    post_obj = Post.get_or_none(pk=pid,status=1,can_comment=True)
    if post_obj is None:
        return FailResp(code=30301, msg="文章不存在!")
    comment.post_id = pid
    if comment.replied_id is 0:
        # 将replied_id设为None
        comment.replied_id = None
    else:
        comment.replied_id = cid
    try:
        await CommentModel.create(**comment.dict())
        return SuccessResp(data="创建成功!")
    except OperationalError:
        return FailResp(code=30301, msg="创建失败!")


@router.delete("/{cid}", summary="删除评论")
async def delete_comment(req: Request, cid: int = Path(..., gt=0)):
    comment_obj = await get_comment_by_id(cid)
    if comment_obj is None:
        return FailResp(code=30201, msg="评论不存在!")
    await CommentModel.filter(pk=cid).update(status=9)
    return SuccessResp(data="删除成功!")
    
    
@router.get('/{cid}', summary="查询评论")
async def get_comment(req: Request,cid: int = Path(..., gt=0)):
    comment_obj = await get_comment_by_id(cid)
    if comment_obj is None:
        return FailResp(code=30201, msg="评论不存在!") 
    data = parse_obj_as(CommentOut, comment_obj)
    return SingleResp[CommentOut](data=data)


@router.put('/reviewed/{cid}',summary="更新评论状态")
async def get_post_published(req: Request,cid: int = Path(..., gt=0)):
    '''
    评论审核状态
    '''
    get_comment = await CommentModel.get_or_none(pk=cid)
    if get_comment is None:
        return FailResp(code=30201, msg="文章不存在!")
    if get_comment.is_reviewed:
        get_comment.is_reviewed = False
    else:
        get_comment.is_reviewed = True
    await get_comment.save()
    msg = f"评论 [ID={get_comment.pk}] 已"
    msg += "审核" if get_comment.is_reviewed else "取消"
    return SuccessResp(data=msg)


@router.put("/{cid}", summary="修改评论")
async def comment_update(req: Request, comment: CommentUpdate, cid: int = Path(..., gt=0)):
    comment_obj = await get_comment_by_id(cid)
    if comment_obj is None:
        return FailResp(code=30201, msg="评论不存在!")
    if comment.replied_id is 0:
        #将replied_id设为None
        comment.replied_id = None
    if comment_obj.body != comment.body:
        try:
            async with in_transaction():
                # 更新分类
                update_data = comment.dict(exclude_unset=True, exclude_none=True)
                await comment_obj.update_from_dict(update_data)
                await comment_obj.save()
        except OperationalError:
            return FailResp(code=30301, msg="更新失败!")
    return SuccessResp(data="更新成功!")


@router.get('/post/{pid}', summary="查询对应文章id的评论")
async def get_comments(req: Request,pid: int = Path(..., gt=0)):
    post_obj = Post.get_or_none(pk=pid,status=1,can_comment=True)
    if post_obj is None:
        return FailResp(code=30301, msg="文章不存在!")
    comments_list = await CommentModel.filter(post_id=pid, status__not=9).all()
    return MultiResp[CommentOut](data=comments_list)